package com.harboursoftware.xstorage.db.sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.harboursoftware.xstorage.ac.AccessControlPolicy;
import com.harboursoftware.xstorage.ac.Grant;
import com.harboursoftware.xstorage.model.XUser;
/**
 * 
 * @author Simon Leung
 * @since 0.1
 */
class AcpRowProcessor extends BaseRowProcessor {
    private RowProcessor grantRowProcessor = new GrantRowProcessor();
    private ResultSetHandler<List<Grant>> grantBeanListHandler = new BeanListHandler<Grant>(Grant.class, grantRowProcessor);
    private DatabaseProvider databaseProvider;
    
    public AcpRowProcessor(DatabaseProvider databaseProvider) {
        this.databaseProvider =  databaseProvider;
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public <T> T toBean(ResultSet rs, Class<T> type) throws SQLException {  
        String acpId = rs.getString("id");
        String ownerId = rs.getString("onwer_id");
        String ownerDisplayName = rs.getString("onwer_display_name");
        XUser onwer = new XUser(ownerId, ownerDisplayName);
        List<Grant> grants = listGrantsOfAcp(acpId);

        return (T)new AccessControlPolicy(onwer, grants);
    }
    
    private List<Grant> listGrantsOfAcp(String acpId) throws SQLException {
        Connection connection;
        connection = databaseProvider.getConnection();

        String sql = "SELECT * FROM x_grant WHERE acp=?";
        QueryRunner sqlRunner = new QueryRunner();
        List<Grant> grants = sqlRunner.query(connection, sql, grantBeanListHandler, acpId);
        DbUtils.closeQuietly(connection);
        return grants;
    }
}
